// Theme Switcher
// 主题切换功能

// 获取当前主题（默认为深色模式）
let currentTheme = localStorage.getItem('theme') || 'dark';

// 应用主题
function applyTheme(theme) {
    if (theme === 'light') {
        document.body.classList.add('light-theme');
        document.body.classList.remove('dark-theme');
    } else {
        document.body.classList.add('dark-theme');
        document.body.classList.remove('light-theme');
    }
    
    // 更新主题切换按钮状态
    updateThemeSwitcherButtons(theme);
    
    // 保存主题选择
    localStorage.setItem('theme', theme);
    currentTheme = theme;
    
    // 触发自定义事件，通知其他组件主题已更改
    const event = new CustomEvent('themeChanged', { detail: { theme: theme } });
    document.dispatchEvent(event);
}

// 切换主题
function toggleTheme() {
    const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    applyTheme(newTheme);
}

// 更新主题切换按钮状态
function updateThemeSwitcherButtons(theme) {
    const themeButtons = document.querySelectorAll('.theme-switcher button');
    themeButtons.forEach(button => {
        button.classList.remove('active');
        if ((theme === 'dark' && button.getAttribute('data-theme') === 'dark') ||
            (theme === 'light' && button.getAttribute('data-theme') === 'light')) {
            button.classList.add('active');
        }
    });
}

// 初始化主题切换器
function initThemeSwitcher() {
    // 创建主题切换器容器
    const themeSwitcher = document.createElement('div');
    themeSwitcher.className = 'theme-switcher';
    
    // 创建深色模式按钮
    const darkButton = document.createElement('button');
    darkButton.setAttribute('data-theme', 'dark');
    darkButton.innerHTML = '<i class="fas fa-moon"></i>';
    darkButton.title = '深色模式';
    darkButton.addEventListener('click', () => applyTheme('dark'));
    
    // 创建浅色模式按钮
    const lightButton = document.createElement('button');
    lightButton.setAttribute('data-theme', 'light');
    lightButton.innerHTML = '<i class="fas fa-sun"></i>';
    lightButton.title = '浅色模式';
    lightButton.addEventListener('click', () => applyTheme('light'));
    
    // 将按钮添加到容器
    themeSwitcher.appendChild(darkButton);
    themeSwitcher.appendChild(lightButton);
    
    // 将主题切换器添加到导航控制区域
    const navControls = document.querySelector('.nav-controls');
    if (navControls) {
        navControls.appendChild(themeSwitcher);
    }
    
    // 应用保存的主题或默认主题
    applyTheme(currentTheme);
}

// 当DOM加载完成后初始化主题切换器
document.addEventListener('DOMContentLoaded', initThemeSwitcher);